timeApi = require "timeApi"
wifiCong = require "wifiConfig"

function init_OLED(sda,scl)
  sla = 0x3c
  i2c.setup(0, sda, scl, i2c.SLOW)
  disp=u8g2.ssd1306_i2c_128x64_noname(0,sla)
  disp:setFont(u8g2.font_unifont_t_symbols)
--  disp:setPowerSave(1)
  disp:setFontPosTop()
end

function connect_WIFI (timer)
  local has = false
  wifi.sta.getap(function(t)
    for k, v in pairs(t) do
      if k == wifiCong.sta_conf.ssid then
        has = true
        break
      end
    end
    if has then
      wifi.sta.config(wifiCong.sta_conf)
      wifi.sta.connect()

      disp:clearBuffer()
      disp:drawStr(0, 0, "welcome...")
      disp:drawStr(0, 15, "connect WIFI:")
      disp:drawStr(0, 31, wifiCong.sta_conf.ssid)
      disp:drawStr(0, 47, wifiCong.sta_conf.pwd)
      disp:sendBuffer()
      if timer and timer:state() then
        timer:stop()
      end
    else
      disp:clearBuffer()
      disp:drawStr(0, 0, "welcome...")
      disp:drawStr(0, 15, "no search WIFI:")
      disp:drawStr(0, 31, wifiCong.sta_conf.ssid)
      disp:sendBuffer()
    end
  end)
end

function init_WIFI()
  -- wifi init
  wifi.setmode (wifiCong.mode)
  -- callback in get ip
  wifiCong.sta_conf.got_ip_cb = function(IP, netmask, gateway)
    -- request network time info
    timeApi:update(function()
      -- loop count time
      tmr:create():alarm(1000, 1, function()
        timeApi:show()
      end)
    end)
  end
  disp:clearBuffer()
  disp:drawStr(0, 0, "welcome...")
  disp:sendBuffer()
  --connect_WIFI()
  local timer = tmr:create()
  timer:alarm (5*1000, 1, function() connect_WIFI (timer) end)
end
init_OLED(3, 4)
init_WIFI()
